//
//  RealmPage.swift
//  ios-template
//
//  Created by lvyii000 on 2021/8/23.
//  Copyright © 2021 耳東陳. All rights reserved.
//

import SwiftUI
import RealmSwift

struct RealmPage: View {
    
    @EnvironmentObject var state: AppState
    @State var walletName = ""
    @State var walletList: Array<Wallet> = []
    
    var body: some View {
        VStack{
            BaseCell(title: AnyView(TextField("请输入钱包名称", text: self.$walletName)),leading: AnyView(Text("添加钱包")),trailing: AnyView(Button(action: addWallet, label: {
                Text("添加")
            })), clickable: false).padding()
            List{
                Section(header: Text("数据库钱包信息")){
                    ForEach(walletList, id: \.self){ item in
                        BaseCell(title: AnyView(Text("钱包名称：\(item.name)"))
//                                 ,  trailing: AnyView(Button(action:{
//                            self.delWallet(wallet: item)
//                        }, label: {
//                            Text("删除")
//                        }))
                                 , clickable: false)
                    }
                }
            }.listStyle(SidebarListStyle())
        }.onAppear(perform: {
            DispatchQueue.main.async {
//                for item in WalletDao.getWalletList() {
//                    walletList.append(item)
//                }
                walletList = RealmManager.shared.getObjects(type: Wallet.self)
            }
            
        })
    }
   
    // 添加钱包
    func addWallet() -> Void {
        if walletName.count > 0 {
            let wallet = Wallet()
            wallet.name = self.walletName
            self.walletName = ""
            DispatchQueue.main.async {
                RealmManager.shared.write(item: wallet)
                walletList = RealmManager.shared.getObjects(type: Wallet.self)
            }
        }
    }
    
    // 删除钱包
    func delWallet(wallet: Wallet) -> Void {

        DispatchQueue.main.async {
//            RealmManager.shared.delete(item: wallet)
//            walletList = RealmManager.shared.getObjects(type: Wallet.self)
        }
        
    }
}

struct RealmPage_Previews: PreviewProvider {
    static var previews: some View {
        RealmPage()
    }
}
